package com.yunao.service.report.esou;




import com.yunao.entity.AloneReport;
import com.yunao.service.AlonereportService;
import com.yunao.service.ReportService;
import com.yunao.service.report.Convert;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 自动报告定时器
 *
 * @author glt
 *
 */
public class ReportTask2 extends TimerTask {

	// 自动报告发送时间
	private static final int REPORT_HOUR = 7;

	private int maximum = 5;

	private int index = 1;

	private AlonereportService alonereportService;
	private ReportService reportService;
	public ReportTask2(AlonereportService alonereportService, ReportService reportService) {
		try {
			maximum = Convert.getInt("3");
            this.alonereportService=alonereportService;
            this.reportService = reportService;
		} catch (Exception e) {

		}
	}

	public void run() {
//		Calendar c = Calendar.getInstance();
//		c.setTime(new Date());
//		int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
//		if (REPORT_HOUR != hourOfDay)
//			return;
		System.out.println("第" + index+ "次自动报告！");
		// 所有需要使用自动报告的专题
		List<AloneReport> aloneReports = alonereportService.findByNeed("1");
		// 预警专题数
		int total = aloneReports.size();
		// 线程池
		ExecutorService pool = Executors.newCachedThreadPool();
		// 同时执行的线程数
		//int len = total / maximum + 1;

		int len=maximum;
		int avg=total/len;
		if(avg==0)
		{
			len=total;
			avg=1;
		}
		//System.out.println("test://len/"+len);
		for (int i = 0; i < len; i++) {

			int fromIndex = i * avg;
			int toIndex = i == len - 1 ? total : fromIndex + avg;
			//System.out.println("test://fromindex-toindex/"+fromIndex+"-"+toIndex);

			pool.execute(new ReportThread2(aloneReports.subList(fromIndex, toIndex),reportService));
		}
		// 线程池关闭
		pool.shutdown();
	}


	public void currentreport(int id) {
		System.out.println("及时报告发送中");
		// 所有需要使用自动报告的专题
		List<AloneReport> aloneReports = alonereportService.findByNeedAndId("1",id);

		System.out.println("及时报告发送中2");

		// 预警专题数
		int total = aloneReports.size();
		// 线程池
		ExecutorService pool = Executors.newCachedThreadPool();
		// 同时执行的线程数
		int len = total / maximum + 1;
//		System.out.println("test://len/"+len);
		for (int i = 0; i < len; i++) {

			int fromIndex = i * maximum;
			int toIndex = i == len - 1 ? total : fromIndex + maximum;
			//System.out.println("test://fromindex-toindex/"+fromIndex+"-"+toIndex);

			pool.execute(new ReportThreadc2(aloneReports.subList(fromIndex, toIndex),reportService));
		}
		// 线程池关闭
		pool.shutdown();
	}

}
